<template>
  <div class="abnormal-transactions">
    <div class="page-header">
      <div class="header-left">
        <h3>异常交易记录</h3>
        <p>查看和处理交易异常情况</p>
      </div>
      <div class="header-right">
        <el-button @click="refreshData">刷新</el-button>
        <el-button type="primary" @click="goToSettings">监控设置</el-button>
      </div>
    </div>

    <div class="filter-section">
      <el-card>
        <el-form :inline="true" :model="filters">
          <el-form-item label="账号">
            <el-select v-model="filters.accountId" placeholder="选择账号" clearable style="width: 200px">
              <el-option
                v-for="account in accountList"
                :key="account.id"
                :label="account.name"
                :value="account.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="queryData">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="table-section">
      <el-card>
        <el-table
          :data="transactionList"
          :loading="loading"
          stripe
          style="width: 100%">

          <el-table-column prop="accountName" label="账号" width="120" />

          <el-table-column prop="symbol" label="币种" width="100">
            <template #default="{ row }">
              {{ getSymbolFromRemark(row.remark) }}
            </template>
          </el-table-column>

          <el-table-column prop="plannedAmount" label="计划金额" width="140">
            <template #default="{ row }">
              {{ formatAmount(row.plannedAmount) }}
            </template>
          </el-table-column>

          <el-table-column prop="actualAmount" label="实际金额" width="140">
            <template #default="{ row }">
              {{ formatAmount(row.actualAmount) }}
            </template>
          </el-table-column>

          <el-table-column prop="slippage" label="磨损量" width="140">
            <template #default="{ row }">
              {{ formatAmount(row.slippage) }}
            </template>
          </el-table-column>

          <el-table-column prop="slippageRate" label="磨损率" width="120">
            <template #default="{ row }">
              <el-tag :type="row.isAbnormal ? 'danger' : 'success'">
                {{ formatPercentage(row.slippageRate) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="txHash" label="交易哈希" width="200">
            <template #default="{ row }">
              <span class="tx-hash" :title="row.txHash">
                {{ formatTxHash(row.txHash) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="alertSent" label="告警状态" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.alertSent" type="warning">已告警</el-tag>
              <el-tag v-else type="info">待处理</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="tradeTime" label="交易时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.tradeTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.accountStatus === 'paused_by_monitor'"
                type="success"
                size="small"
                @click="resumeAccount(row.accountId)">
                恢复运行
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="viewDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/request'

const router = useRouter()

// 状态管理
const loading = ref(false)
const accountList = ref([])
const transactionList = ref([])

// 筛选条件
const filters = reactive({
  accountId: null
})

const dateRange = ref([])

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 计算属性
const startDate = computed(() => dateRange.value?.[0] || null)
const endDate = computed(() => dateRange.value?.[1] || null)

// 初始化
onMounted(async () => {
  await loadAccountList()
  await queryData()
})

// 加载账号列表
const loadAccountList = async () => {
  try {
    const response = await http.get('/accounts')
    accountList.value = response.data.list || []
  } catch (error) {
    console.error('加载账号列表失败:', error)
  }
}

// 查询数据
const queryData = async () => {
  loading.value = true
  try {
    const params = {
      accountId: filters.accountId,
      startDate: startDate.value,
      endDate: endDate.value,
      page: pagination.page,
      size: pagination.size
    }

    const response = await http.get('/monitor/abnormal-transactions', params)
    transactionList.value = response.data.list || []
    pagination.total = response.data.total || 0

  } catch (error) {
    ElMessage.error('查询异常交易失败')
    console.error('查询异常交易失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.accountId = null
  dateRange.value = []
  pagination.page = 1
  queryData()
}

// 刷新数据
const refreshData = () => {
  queryData()
}

// 分页处理
const handleSizeChange = () => {
  pagination.page = 1
  queryData()
}

const handleCurrentChange = () => {
  queryData()
}

// 恢复账号运行
const resumeAccount = async (accountId) => {
  try {
    await ElMessageBox.confirm('确认恢复该账号的交易脚本运行？', '确认操作', {
      type: 'warning'
    })

    await http.put(`/accounts/${accountId}/resume`)
    ElMessage.success('账号已恢复运行')
    await queryData()

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复账号失败')
      console.error('恢复账号失败:', error)
    }
  }
}

// 查看详情
const viewDetail = (row) => {
  // 这里可以打开详情对话框或跳转到详情页面
  console.log('查看交易详情:', row)
}

// 跳转到设置页面
const goToSettings = () => {
  router.push('/system/settings')
}

// 工具方法
const formatAmount = (amount) => {
  return amount ? parseFloat(amount).toFixed(8) : '0.00000000'
}

const formatPercentage = (rate) => {
  return rate ? (parseFloat(rate) * 100).toFixed(4) + '%' : '0.0000%'
}

const formatTxHash = (hash) => {
  return hash ? `${hash.substring(0, 10)}...${hash.substring(hash.length - 8)}` : '-'
}

const formatDateTime = (dateTime) => {
  return dateTime ? new Date(dateTime).toLocaleString() : '-'
}

const getSymbolFromRemark = (remark) => {
  // 从备注中提取币种信息，这里可以根据实际格式调整
  return '未知币种'
}
</script>

<style lang="scss" scoped>
.abnormal-transactions {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .filter-section,
  .table-section {
    margin-bottom: 20px;
  }

  .tx-hash {
    font-family: monospace;
    cursor: pointer;
  }

  .pagination-wrapper {
    margin-top: 20px;
    text-align: center;
  }
}
</style>